import Vue from 'vue'
import VueRouter from 'vue-router'
// 一级路由
import Home from '@/views/Home'
import Login from '@/views/Login'

// 二级路由
import Users from '@/components/Users'
import Roles from '@/components/Roles'
import Rights from '@/components/Rights'
import Params from '@/components/Params'
import Reports from '@/components/Reports'
import Orders from '@/components/Orders'
import Goods from '@/components/Goods'
import Categories from '@/components/Categories'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    children: [
      {
        path: '/users',
        name: 'Users',
        component: Users
      },
      {
        path: '/roles',
        name: 'Roles',
        component: Roles
      },
      {
        path: '/rights',
        name: 'Rights',
        component: Rights
      },
      {
        path: '/reports',
        name: 'Reports',
        component: Reports
      },
      {
        path: '/params',
        name: 'Params',
        component: Params
      },
      {
        path: '/orders',
        name: 'Orders',
        component: Orders
      },
      {
        path: '/goods',
        name: 'Goods',
        component: Goods
      },
      {
        path: '/categories',
        name: 'Categories',
        component: Categories
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()

  const token = window.sessionStorage.getItem('token')

  if (token) return next()

  if (from.path !== '/login') router.push('/login')
})
export default router
